package com.sword.service.impl.finance;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.sword.constant.MessageConstant;
import com.sword.page.PageResult;
import com.sword.page.QueryPageBean;
import com.sword.pojo.finance.Receivables;
import com.sword.service.finance.ReceivablesService;
import com.sword.service.impl.BasicBaseServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.Date;

@Service
@Transactional
public class ReceivablesServiceImpl extends BasicBaseServiceImpl<Receivables> implements ReceivablesService {
    /**
     * 分页查询应收单
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult queryReceivables(QueryPageBean queryPageBean) {

        QueryWrapper<Receivables> wrapper = new QueryWrapper<>();
        String queryString = queryPageBean.getQueryString();
        // 如果queryString有值
        if (queryString != null) {
            Receivables receivables = new Receivables();
            Field[] fields = receivables.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                //有的字段是用private修饰的 将他设置为可读
                fields[i].setAccessible(true);
                if(fields[i].getName().endsWith("Date")){
                    continue;
                }
                wrapper.like(fields[i].getName(),queryString).or();
            }
        }
        IPage<Receivables> ipage = super.queryPageList(wrapper,queryPageBean.getPage(),queryPageBean.getLimit());
        return new PageResult(0, MessageConstant.QUERY_RECEIVABLES_SUCCESS, ipage.getTotal(), ipage.getRecords());
    }

    @Override
    public Integer addReceivables(Receivables receivables) {
        receivables.setSubmitdate(new Date());
        receivables.setReviewdate(new Date());
        return super.save(receivables);
    }

    @Override
    public Integer editReceivables(Receivables receivables) {
        return super.update(receivables);
    }

    @Override
    public Integer examineBuyorderDetail(Receivables receivables) {
        String userId = (String) SecurityUtils.getSubject().getSession().getAttribute("loginUser");
        receivables.setExamineid(userId);
        receivables.setStatus(1);
        return super.update(receivables);
    }

    @Override
    public Integer unexamineBuyorderDetail(Receivables receivables) {
        receivables.setExamineid("");
        receivables.setStatus(0);
        return super.update(receivables);
    }

    @Override
    public Integer deleteReceivables(Integer id) {
        return super.deleteById(Long.valueOf(id));
    }
}
